import random

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from ronglian_sms_sdk import SmsSDK
# Create your views here.
from django.views import View
from django_redis import get_redis_connection


from celery_tasks.sms.tasks import send_message




class SmsCodeView(View):
    def get(self, request, mobile):
        # 获取用户的图片验证码

        redis_connect = get_redis_connection('verify_code')


        delay_captcha = redis_connect.get(f'{mobile}time')
        if delay_captcha:
            return JsonResponse({'code': 400, 'errmsg': '获取验证码过于频繁，请稍后再试'})

        mobile_code = random.randint(100000, 999999)
        send_message.delay(mobile,mobile_code)

        print(mobile_code)
        ppl = redis_connect.pipeline()
        # 手机验证码倒计时,防止频繁发送验证码
        ppl.setex(f'{mobile}time', 60, 1)
        # 将验证码保存redis数据库10分钟
        ppl.setex(f'mobile_code{mobile}', 600, mobile_code)
        ppl.execute()
        return JsonResponse({'success': True, 'message': '验证码发送成功','sms_code':mobile_code})

